package com.sumer.psychology.friend.domain.service;

import com.sumer.psychology.common.Assert;
import com.sumer.psychology.common.domain.model.AbstractDomainService;
import com.sumer.psychology.friend.domain.model.*;

/**
 * 朋友关系服务
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/8/28
 * Time: 15:44
 */
public class FriendshipService extends AbstractDomainService {
    private MemberRepository memberRepository;

    public FriendshipService(MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }

    /**
     * 确认两个成员的朋友关系
     *
     * @param requesterId 申请者
     * @param acceptorId  接受者
     */
    public void confirmFriendshipBetween(MemberId requesterId, MemberId acceptorId, String messageId) {
        Member requester = memberRepository().memberOfId(requesterId);
        Member acceptor = memberRepository().memberOfId(acceptorId);

        Assert.notNull(requester, "请求者不存在");
        Assert.notNull(acceptor, "接受者不存在");

        requester.addFriend(acceptor);
        acceptor.addFriend(requester);

        apply(new FriendAddedEvent(requesterId, acceptorId, messageId));
    }

    /**
     * 删除一个朋友关系
     *
     * @param requesterId 申请者
     * @param deleteId    接受者
     */
    public void deleteFriendshipBetween(MemberId requesterId, MemberId deleteId) {
        Member requester = memberRepository().memberOfId(requesterId);
        Member deleteFriend = memberRepository().memberOfId(deleteId);

        Assert.notNull(requester, "请求者不存在");
        Assert.notNull(deleteFriend, "待删除者不存在");

        requester.deleteFriend(deleteFriend);
        deleteFriend.deleteFriend(requester);

        apply(new FriendDeletedEvent(requesterId, deleteId));
    }

    public MemberRepository memberRepository() {
        return memberRepository;
    }

}
